import { constantRouterMap, asyncRouterMap, personalRouterMap } from '@/config/router.config'
import { generatorDynamicRouter, generatorRouteGroup, constantRouterComponents } from '@/router/generator-routers'
import { getAuth } from '@/api/auth'
import { treeFilterBySelf } from '@/utils/util'

/**
 * 将window.app.$remoteModules里的远程模块拼成路由挂在到constantRouterComponents
 */
function addRemoteRouterComponents() {
  const remoteModules = window.app.$remoteModules
  if (remoteModules) {
    Object.keys(remoteModules).forEach(key => {
      if (Object.hasOwnProperty.call(remoteModules, key)) {
        constantRouterComponents[key] = remoteModules[key]
      }
    })
  }
}

/**
 * 将router树里的actions扁平化为一个数组，供action.js使用，递归方法
 * @param {*} routers 路由
 * @param {*} actions 数组
 */
function flatActions(routers, actions) {
  if (!!routers && Array.isArray(routers)) {
    for (const router of routers) {
      if (Object.hasOwnProperty.call(router, 'actions') && Array.isArray(router.actions)) {
        actions.push({
          permissionId: router.name,
          actionList: router.actions.map(a => a.action)
        })
      }
      if (Object.hasOwnProperty.call(router, 'children') && Array.isArray(router.children)) {
        flatActions(router.children, actions)
      }
    }
  }
}

const auth = {
  state: {
    routerGroup: {
      // 路由组键值对
    },
    addRouters: [], // pureRouters挂进首页children之后的路由
    routers: constantRouterMap, // addRouters和登录页等常驻路由合并之后的完整路由
    industrialModelRouters: {}, // 工业模型路由
    industrialBigDataRouters: {},// 工业大数据管理
    dataModelingRouters: {},// 数据建模分析平台
    DevOperAndcenterRouters: [], // 开发运维中心路由
    actions: [], // 扁平化后的页面中组件可使用性（查看、新建、编辑、删除、导入、导出等）
    access: [] // 能够访问到的模块&组件
  },
  mutations: {
    SET_ROUTERS: (state, pureRouters) => {
      const dynamicRouters = generatorDynamicRouter(pureRouters)
      state.addRouters = dynamicRouters
      state.routers = constantRouterMap.concat(dynamicRouters)
    },
    SET_ROUTER_GROUP: (state, fullRouters) => {
      const routerGroup = generatorRouteGroup(fullRouters)
      state.routerGroup = routerGroup
    },
    SET_ACTIONS: (state, actions) => {
      state.actions = actions
    },
    SET_ACCESS: (state, access) => {
      state.access = access
    },
    SET_INDUSTRIALMODELROUTERS(state, routers) {
      state.industrialModelRouters = routers
    },
    SET_DEVOPERANDCENTERROUTERS(state, routers) {
      state.DevOperAndcenterRouters = routers
    },
    SET_INDUSTRIALBIGDATAROUTERS(state, routers) {
      state.industrialBigDataRouters = routers
    },
    SET_DATAMODELINGROUTERS(state, routers) {
      state.dataModelingRouters = routers
    },

  },
  actions: {
    // 获取用户权限（页面访问性）
    GetAuth({ commit }, data) {
      return new Promise((resolve, reject) => {
        getAuth(data)
          .then(res => {
            addRemoteRouterComponents()
            if (data.role === 'super_admin') {
            }
            // const routers = asyncRouterMap
            let routers = []
            routers = treeFilterBySelf(res.data, node => node.status === 1)
            //添加个人中心页面
            let platformManagement = routers.filter(i => i.name === 'platformManagement')[0]
            if (platformManagement) {
              platformManagement.children = platformManagement.children.filter(i => i.name !== 'account')
              platformManagement.children.push(personalRouterMap.children[0])
            } else {
              if (routers[0] && routers[0].name === "authenticationCenter") {
                routers.splice(1, 0, personalRouterMap)
              } else {
                routers.splice(0, 0, personalRouterMap)
              }
            }
            const industrialModelRouters = routers.filter(i => i.name === 'industrialModel')[0]
            const industrialBigDataRouters = routers.filter(i => i.name === 'industrialBigData')[0]
            const dataModelingRouters = routers.filter(i => i.name === 'dataModeling')[0]
            commit('SET_ROUTERS', routers.filter(i => !['dataModeling', 'industrialModel', 'industrialBigData'].includes(i.name)))
            commit('SET_DEVOPERANDCENTERROUTERS', routers.filter(i => !['dataModeling', 'industrialModel', 'industrialBigData'].includes(i.name)))
            commit('SET_INDUSTRIALMODELROUTERS', industrialModelRouters)
            commit('SET_INDUSTRIALBIGDATAROUTERS', industrialBigDataRouters)
            commit('SET_DATAMODELINGROUTERS', dataModelingRouters)
            const actions = []
            flatActions(routers, actions)
            if (actions.length > 0) {
              actions.forEach(per => {
                if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
                  const action = per.actionEntitySet.map(i => i.action)
                  per.actionList = action
                }
              })
              commit('SET_ACTIONS', actions)
            }
            resolve(res)
          })
          .catch(error => {
            const routers = []
            commit('SET_ROUTERS', routers)
            const actions = []
            commit('SET_ACTIONS', actions)
            reject(error)
          })
      })
    }
  }
}

export default auth
